jQuery(document).on("click", "#submit_note", function() {	
	$("#note_content").val( $(".note_content_richtext").html() );
	tinymce.triggerSave();
	$.ajax({
		url		: 		"write.php?action=write",
		type	: 		"POST",
		data	:		 $( "#write_note" ).serialize(),
		dataType:		"html",
		valid_elements : '+*[*]'
	}).done(function(response) {
		results = JSON.parse(response);
		if ( (results.success) && (results.success == "success" ) ) {
			window.location.replace( results.redirect_to );			
		}
		if ( results.errors != "") {
			$("#write_note_outcome").css("display","block");
			$("#write_note_outcome").html(results.errors);
			return false;
		}
		return false;
	}).error(function(response) {
		$("#write_note_outcome").css("display","block");
		$("#write_note_outcome").html("Sorry, but something went wrong while writing the note. Please retry.");
	});
	return false;
	
});


/*
jQuery(document).on("click", ".edit_note", function() {	
	$.get( $(this).attr("href"),function(response) {
		$("#edit_note_popup").html(response);
		$("#edit_note_popup").css("display", "block");
		$("#edit_note_popup").css("z-index", "500");
	});	
	return false;
});

*/


jQuery(document).on("click", ".delete_note", function() {
	response = confirm("Are you sure about deleting the note?");
	if ( response == true ) {
		$.get( $(this).attr("href"), function(response) {
			results = JSON.parse(response);
			if ( (results.success) && ( results.success.length > 0 ) ) {
				id = "#" + "note-" + results.note_id;
				console.log($(id));
				$("#notify").css("display","block");
				$("#notify").html(results.success);
				jQuery(id).remove();
			}
			if ( (results.errors) && ( results.errors.length > 0 ) ) {			
				$("#notify").css("display","block");
				$("#notify").html(results.errors);			
			}
		});	
		return false;
	}
	return false;
});

$(document).on("click", "#submit_edits", function() {
	
	$("#note_content").val( $(".note_content_richtext").html() );
	tinymce.triggerSave();
	$.ajax({
		url		: 		"notes.php?save_edits",
		type	: 		"POST",
		data	:		 $( "#form_edit_note" ).serialize(),
		dataType:		"html",		
	}).done(function(response) {
		$("#response").html(response);
		return false;
	}).error(function(response) {
		alert(response);
	});
	return false;	
});



/* 	TODO: submit only when focus is not on
	text areas
$(document).keyup(function(e) {
    if ( e.which == 13 ) {
		$.ajax({
			url		: 		"notes.php?save_edits",
			type	: 		"POST",
			data	:		$( "#form_edit_note" ).serialize(),
			dataType:		"text",		
		}).done(function(response) {
			$("#response").html(response);
			return false;
		}).error(function(response) {
			alert(response);
		});	
		return false;		
	}
});

*/

/*
jQuery("#my_notes, #my_private_notes, #my_public_notes ").click(function() {
	$.get($(this).attr("href"),function(response) {
		$("#rack").remove();
		if ( jQuery("#box") ) {
			$("#box").append(response);
		}
	});	
	return false;
});

*/

jQuery(".tags_href").click(function() {
	$.get( $(this).attr("href"),function(response) {
		$("#rack").remove();
		if ( jQuery("#box") ) {
			$("#box").append("<div> tagged posts only</div>");
		}
	});
	return false;
});


jQuery(document).on("click", "#tab", function() {

	var target_text = jQuery(".note_content_richtext").text();
	var selectedObj = window.getSelection().toString();
	var selection_starts_at = target_text.indexOf(selectedObj);
	
	console.log(selectedObj);
	console.log( selection_starts_at );
	
	if ( target_text.indexOf( selectedObj ) != -1  ) {
		console.log(target_text.indexOf("<br>"));
	} 
});


jQuery(document).on("click", "#bold", function() {
	var target_text = jQuery(".note_content_richtext").html();
	var selectedObj = window.getSelection();
	var range_at = selectedObj.getRangeAt(0);
	
	if ( selectedObj.toString().length > 0 ) {
		var span_bold = document.createElement("b");
		range_at.surroundContents(span_bold);
	}
	
});

jQuery(document).on("click", "#underline", function() {
	
	var target_text = jQuery(".note_content_richtext").html();
	var selectedObj = window.getSelection();
	var range_at = selectedObj.getRangeAt(0);
	
	if ( selectedObj.toString().length > 0 ) {
		var span_underline = document.createElement("u");
		range_at.surroundContents(span_underline);
	}
	
});



jQuery(document).on("click", "#italic", function() {

	var target_text = jQuery(".note_content_richtext").html();
	var selectedObj = window.getSelection();
	var range_at = selectedObj.getRangeAt(0);
	
	if ( selectedObj.toString().length > 0 ) {
		var span_italic = document.createElement("i");
		range_at.surroundContents( span_italic );
	}
	
});

$("#user_login").click(function() {
	$("#user_authentication").load("user.php?login_form");
	$("#user_authentication").css("display", "block");
	$("#user_authentication").css("z-index", "500");
	return false;
});


$(document).on("click", "#login", function(e) {
	login();
});

function login() {
	$("#login_outcome").text();
	$.ajax({
		url		: 		"user.php?login",
		type	: 		"POST",
		data	:		 $("#login_form").serialize(),
		dataType:		"text",		
	}).done(function(response) {
		results = JSON.parse(response);
		if ( results.success ) {
			$("#login_outcome").css("display", "block");
			$("#login_outcome").html(results.success);
			window.location = results.redirect_to;
		}
		
		if ( results.errors ) {
			$("#login_outcome").css("display", "block");
			$("#login_outcome").html(results.errors);	
		}		
		
		return false;
		
	}).error( function(response) {
		$("#login_outcome").html("<span>There was an internal error while logging in. Please retry.</span>");
		return false;
	});
	return false;
}

$(document).on("click", "#cancel_login", function() {
	$("#modal_login").remove();
	$("#user_authentication").css("z-index", "-99999");
});


$(document).on("click", "#cancel_register_user", function() {
	$("#user_authentication").css("z-index", "-99999");
	$("#user_authentication").css("display", "none");
	
	$("#user_registration").css("z-index", "-99999");
	$("#user_registration").css("display", "none");
	
});

$(document).on("click", "#create_account", function() {
	$("#user_authentication").css("display", "none"); // Toggle visibility to user_registration from user_authentication.
	
	$("#user_registration").load("user.php?register_form");
	$("#user_registration").css("display","block");
	$("#user_registration").css("z-index","500");	
	
});



$(document).on("click", "#get_reset_password_form", function() {
	$("#user_authentication").css("display", "none"); // Toggle visibility to user_passwordreset from other forms.
	$("#user_registration").css("display", "none");
	$("#user_authentication").css("z-index", 0); // Toggle visibility to user_passwordreset from other forms.
	$("#user_registration").css("z-index", 0);
	
	console.log("here");
	$("#user_passwordreset").load("user.php?passwordreset_form");
	$("#user_passwordreset").css("display","block");
	$("#user_passwordreset").css("z-index","500");	
	
});



$(document).on("click", "#register_account", function() {
	jQuery("#registeration_outcome").text("");	
	$.ajax({
		url		: 		"user.php?register",
		type	: 		"POST",
		data	:		 $("#register_form").serialize(),
		dataType:		"text",		
	}).done(function(response) {
		results = JSON.parse(response);
		
		if ( ( results.errors ) && (results.errors.length > 0 ) ) {
			$("#registeration_outcome").css("display","block");
			jQuery("#registeration_outcome").html(results.errors);
		}
		
		if ( (results.success) && ( results.success.length > 0 ) ) {
			jQuery("#registeration_outcome").html(results.success);
			// Open up the login form now that the registration is successful.
			$("#user_authentication").css("display","block");
			$("#login_form").find('input[type=text],input[type=password]').val('');
			$("#login_form input[name=username]").val(results.registered_user);
			$("#user_registration").css("display","none");
			jQuery("#login_outcome").html("User registration successful. You may login using the credentials supplied." );			
			jQuery("#login_outcome").css("display","block");			
		}		
		return false;
	}).error(function( response ) {
		jQuery("#registeration_outcome").html( "There was an internal error while registering user. Please retry." );
		return false;
	});
	return false;
	
});


$(document).on("click", "#reset_password", function() {
	jQuery("#passwordreset_outcome").text("");	
	$.ajax({
		url		: 		"user.php?password_reset",
		type	: 		"POST",
		data	:		 $("#passwordreset_form").serialize(),
		dataType:		"text",		
	}).done(function(response) {
		results = JSON.parse(response);
		
		if ( ( results.errors ) && (results.errors.length > 0 ) ) {
			$("#passwordreset_outcome").css("display","block");
			jQuery("#passwordreset_outcome").html(results.errors);
		}
		
		if ( (results.success) && ( results.success.length > 0 ) ) {
			jQuery("#passwordreset_outcome").html(results.success);
			// Open up the login form now that the registration is successful.
			$("#user_authentication").css("display","block");
			$("#login_form").find('input[type=text],input[type=password]').val('');
			$("#login_form input[name=username]").val(results.user_who_reset_password);
			$("#user_registration").css("display","none");
			jQuery("#login_outcome").html("Password has been reset successfully. Try logging in using the new password." );			
			jQuery("#login_outcome").css("display","block");
		}		
		return false;
	}).error(function( response ) {
		jQuery("#registeration_outcome").html( "There was an internal error resetting the password. Please retry." );
		return false;
	});
	return false;	
});

$(document).on("click", ".get_notes_by_author", function() {
	$("#user_registration").load("user.php?register_form");
});

$(document).on("keydown", ".note_content_richtext", function(e) {
	 e.preventDefault();
     if (e.keyCode == 13) {
		if ( this.lastChild.nodeName.toLowerCase() != "br" );
		this.appendChild( document.createElement("br") );
     return false;
    }
});


$("#note_title").focusout(function() {
	if ( $("#note_title").val().length > 1 ) {
		note_title=$("#note_title").val();
		$.get("notes.php?load_suggestions&for_title=" + encodeURI(note_title), function(suggestions) {
			suggestions = suggestions.trim();
			if ( suggestions.length > 1 ) {
				$("#suggestions").html(suggestions);
				jQuery("#write_note_suggestions").css("display", "block");
			} else {
				jQuery("#write_note_suggestions").css("display", "none");
			}
		});		
	} else {
		jQuery("#write_note_suggestions").css("display", "none");
	}	
});


$(".get_comments").click(function() {
	$("#comments_writeup").load($(this).attr("href"));
	$("#comments_writeup").css("display", "block");
	$("#comments_writeup").css("z-index", "500");	
	return false;
});


$(document).on("click", "#write_comments", function() {
	$("#comment_submission_errors").css("display", "none");
	$.ajax({
		url		: 		"notes.php?write_comment",
		type	: 		"POST",
		data	:		 $("#comments_form").serialize(),
		dataType:		"text",		
	}).done(function(response) {
		results = JSON.parse(response);
		
		if ( results.errors == 1 ) {
			$("#comment_submission_errors").html(results.error_text);
			$("#comment_submission_errors").css("display","block");
			return;
		} else {
			//$("#comments_table").html(results.inserted_comment);
			if ( $("#comments_table").find("tr").length != 0 ) {
				$(results.inserted_comment).insertAfter($("#comments_table").find("tr").last());
			} else {
				$("#comments_table").html(results.inserted_comment);
			}
			return false;
		}
	});
	
	return false;
});

$(document).on("click", "#cancel_write_comments", function() {
	$("#comments_writeup").css("display", "none");
});

